package com.juyu.reader.pc.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.juyu.reader.pc.common.Constants;
import com.juyu.reader.pc.model.Book;
import com.juyu.reader.pc.model.BookChapter;
import com.juyu.reader.pc.model.Collection;
import com.juyu.reader.pc.model.Comment;
import com.juyu.reader.pc.model.Page;
import com.juyu.reader.pc.model.Pay;
import com.juyu.reader.pc.model.PayAuto;
import com.juyu.reader.pc.model.User;
import com.juyu.reader.pc.service.BookChapterService;
import com.juyu.reader.pc.service.BookService;
import com.juyu.reader.pc.service.CommentService;
import com.juyu.reader.pc.service.PayService;
import com.juyu.reader.pc.util.StringUtil;

@Controller
@RequestMapping("/book")
public class BookController extends BaseController {
	Logger logger = Logger.getLogger(BookController.class);

	@Autowired
	private BookService bookService;
	@Autowired
	private BookChapterService bookChapterService;

	@Autowired
	private CommentService commentService;

	@Autowired
	private PayService payService;

	/**
	 * 获取某bookId书籍详细信息
	 * @param request
	 * @param book
	 * @return
	 */
	@RequestMapping("/bookInfo")
	public ModelAndView bookInfo(HttpServletRequest request, Book book) {
		Map<String, Object> attrMap = new HashMap<String, Object>();
		book.setBookFlag(-1);
		//根据bookId获取书籍信息
		List<Book> bookList = bookService.findBook(book);
		if (bookList.size() != 1) {
			return this.packModeAndView(request, "/common/error", "非法请求操作！", null);
		} else {
			Book putBook = bookList.get(0);
			attrMap.put("book", putBook);
			attrMap.put("sourceUrl", Constants.SOURCE_URL);
			//用户是否收藏过该书
			List<Collection> collectionList = (List<Collection>) request.getSession()
					.getAttribute(Constants.USER_COLLECTION_LIST);
			boolean isCollection = false;
			if (collectionList != null) {
				for (Collection c : collectionList) {
					if (c.getBookId() == book.getBookId()) {
						isCollection = true;
						break;
					}
				}
			}
			attrMap.put("isCollection", isCollection);
			//TODO 是否购买过该章节？
			List<PayAuto> payAutoList = (List<PayAuto>) request.getSession().getAttribute(Constants.USER_PAY_AUTO_LIST);
			boolean isPayAuto = false;
			if (payAutoList != null) {
				for (PayAuto p : payAutoList) {
					if (p.getBookId() == book.getBookId()) {
						isPayAuto = true;
						break;
					}
				}
			}
			attrMap.put("isPayAuto", isPayAuto);
			//根据t_book_chapter表chapter_seq章节排序，倒序取出1条章节信息
			List<BookChapter> chapterLatestList = bookChapterService.findBookChapterLatestAll(putBook.getBookId());
			if (chapterLatestList.size() == 1) {
				BookChapter outBookChapter = chapterLatestList.get(0);
				if (!StringUtil.isNullOrEmpty(outBookChapter.getChapterContent())) {
					String subChapter = StringUtil.delHTMLTag(outBookChapter.getChapterContent());
					if (subChapter.length() > 200) {
						String tempSubChapter = subChapter.substring(0, 200) + "...";
						outBookChapter.setChapterContent(tempSubChapter);
					}
				}
				attrMap.put("chapterLatest", outBookChapter);
			}
			//获取书籍评论
			Comment findComment = new Comment();
			findComment.setBookId(book.getBookId());
			findComment.setLimit(100);// 不分页，最多显示100
			List<Comment> commentList = commentService.findComment(findComment);
			int commentCount = commentService.countComment(findComment);
			attrMap.put("commentList", commentList);
			attrMap.put("commentCount", commentCount);

			// 排行榜-点击
			Book findClickBook = new Book();
			findClickBook.setBookOrderBy(1);// 默认人气排序，1人气排序，2字数排序，3更新时间排序，4打赏排行，5推荐排行
			findClickBook.setLimit(10);
			List<Book> bookClickList = bookService.findBookOrderBy(findClickBook);
			if (bookClickList.size() >= 10) {
				attrMap.put("bookClick1", bookClickList.get(0));
				attrMap.put("bookClickList", bookClickList.subList(1, 10));
			}
			
			// 推荐榜-强推榜
			findClickBook.setBookOrderBy(5);// 默认人气排序，1人气排序，2字数排序，3更新时间排序，4打赏排行，5推荐排行
			findClickBook.setLimit(10);
			List<Book> bookForwardList = bookService.findBookOrderBy(findClickBook);
			if (bookForwardList.size() >= 10) {
				attrMap.put("bookForward1", bookForwardList.get(0));
				attrMap.put("bookForwardList", bookForwardList.subList(1, 10));
			}
			return this.packModeAndView(request, "/book/bookInfo", null, attrMap);
		}

	}

	/**
	 * 此接口应该没用到
	 * 获取评论列表
	 * @param request
	 * @param book
	 * @return
	 */
	@RequestMapping("/commentList")
	public ModelAndView commentList(HttpServletRequest request, Book book) {
		Map<String, Object> attrMap = new HashMap<String, Object>();
		List<Book> bookList = bookService.findBook(book);
		if (bookList.size() != 1) {
			return this.packModeAndView(request, "/book/error", "非法请求操作！", null);
		} else {
			attrMap.put("book", bookList.get(0));
		}
		Comment findComment = new Comment();
		findComment.setBookId(book.getBookId());
		List<Comment> commentList = commentService.findComment(findComment);
		attrMap.put("commentList", commentList);

		return this.packModeAndView(request, "/book/commentList", null, attrMap);
	}

	/**
	 * /book/chapterList?bookId=1
	 * 立即阅读 按钮
	 * 查看bookId的所有章节
	 * @param request
	 * @param book
	 * @param page
	 * @return
	 */
	@RequestMapping("/chapterList")
	public ModelAndView bookCategory(HttpServletRequest request, Book book, Page page) {
		Map<String, Object> attrMap = new HashMap<String, Object>();
		List<Book> bookList = bookService.findBookById(book.getBookId());
		if (bookList.size() != 1) {
			return this.packModeAndView(request, "/common/error", "非法请求操作！", null);
		} else {
			Book outBook = bookList.get(0);
			attrMap.put("book", outBook);
			BookChapter findBookChapter = new BookChapter();
			findBookChapter.setBookId(book.getBookId());
			findBookChapter.setLimit(0);
			findBookChapter.setOrderBySeq(1);// 1升序，2降序
			List<BookChapter> chapterList = bookChapterService.findBookChapterSimple(findBookChapter);
			attrMap.put("chapterList", chapterList);
			return this.packModeAndView(request, "/book/chapterList", null, attrMap);
		}
	}

	/**
	 * /book/chapterContent?bookId=1&chapterId=1&authorId=26
	 * 点击书籍章节列表中的某一章节，获取该章节详细信息
	 * @param request
	 * @param bookChapter
	 * @return
	 */
	@RequestMapping("/chapterContent")
	public ModelAndView bookContent(HttpServletRequest request, BookChapter bookChapter) {
		// 设置渠道号
		String channelNo = request.getParameter("channelNo");
		if (!StringUtil.isNullOrEmpty(channelNo)) {
			request.getSession().setAttribute("channelNo", request.getParameter("channelNo"));
		}
		User sessionUser = this.getSessionUser(request);
		Map<String, Object> attrMap = new HashMap<String, Object>();
		//获取章节详细内容
		List<BookChapter> chapterList = bookChapterService.findBookChapterById(bookChapter.getChapterId());

		if (chapterList.size() != 1) {
			return this.packModeAndView(request, "/common/error", "非法请求操作！", null);
		} else {
			//获取书籍信息
			List<Book> bookList = bookService.findBookById(bookChapter.getBookId());
			if (bookList.size() == 1) {
				attrMap.put("book", bookList.get(0));
			}
			BookChapter outChapter = chapterList.get(0);
			if (outChapter.getBookStatus() != 1) {
				return this.packModeAndView(request, "/common/error", "该书籍已经下架！", null);
			}
			// 查看章节所在的索引，设置上一章和下一章的索引
			int currentIndex = 0;
			int preChapterId = 0;
			int nextChapterId = 0;
			List<BookChapter> bookIndexList = bookChapterService.findBookChapterIndex(bookChapter);

			for (BookChapter c : bookIndexList) {
				if (c.getChapterId() == outChapter.getChapterId()) {
					currentIndex = bookIndexList.indexOf(c);
				}
			}
			boolean isFirstPage = false;
			boolean isLastPage = false;
			// 第一章
			if (currentIndex == 0) {
				isFirstPage = true;
				preChapterId = bookIndexList.get(0).getChapterId();
				if (bookIndexList.size() > 1) {
					nextChapterId = bookIndexList.get(1).getChapterId();
				} else {
					nextChapterId = preChapterId;
					isLastPage = true;
				}

			} // 最后一章
			else if (currentIndex == (bookIndexList.size() - 1)) {
				preChapterId = bookIndexList.get(currentIndex - 1).getChapterId();
				nextChapterId = bookIndexList.get(currentIndex).getChapterId();
				isLastPage = true;
			} else {
				preChapterId = bookIndexList.get(currentIndex - 1).getChapterId();
				nextChapterId = bookIndexList.get(currentIndex + 1).getChapterId();
				isFirstPage = false;
				isLastPage = false;
			}
			attrMap.put("isFirstPage", isFirstPage);
			attrMap.put("isLastPage", isLastPage);
			attrMap.put("chapter", chapterList.get(0));
			attrMap.put("preChapterId", preChapterId);
			attrMap.put("nextChapterId", nextChapterId);
			// 0默认，1免费，2付费，3半价，4特价全本
			if (bookList.get(0).getBookFree() == 1) {
				return this.packModeAndView(request, "/book/chapterContent", null, attrMap);
			}
			// 查看章节是否付费
			if (outChapter.getChapterFree() == 2) {
				//如果章节金额大于0
				if (outChapter.getChapterAmount() > 0) {
					//如果是付费章节且用户没有登录，则跳转到登录界面
					if (sessionUser == null) {
						return this.packModeAndView(request, "redirect:/user/toLogin", null, null);
					}

					// 查看用户是否已经购买全本
					Pay allPay = new Pay();
					allPay.setUserId(sessionUser.getUserId());
					allPay.setBookId(bookChapter.getBookId());
					allPay.setPayType(3);// 0默认，1阅读消费，2打赏消费，3特价全本
					List<Pay> allPayList = payService.findPayBook(allPay);
					if (allPayList.size() >= 1) {
						return this.packModeAndView(request, "/book/chapterContent", null, attrMap);
					}
					// 查看用户是否已经购买该章节
					Pay findPay = new Pay();
					findPay.setUserId(sessionUser.getUserId());
					findPay.setBookId(outChapter.getBookId());
					findPay.setChapterId(outChapter.getChapterId());
					findPay.setPayType(1);// 0默认，1阅读消费，2打赏消费，3特价全本
					List<Pay> payList = payService.findPayByValidate(findPay);
					if (payList.size() >= 1) {
						return this.packModeAndView(request, "/book/chapterContent", null, attrMap);
					} else {
						//如果用户没有购买过该书、也没购买过该章节则跳转到 /user/payChapter用户付费章节接口
						return this.packModeAndView(request,
								"redirect:/user/payChapter?bookId=" + outChapter.getBookId() + "&chapterId="
										+ outChapter.getChapterId() + "&authorId=" + bookChapter.getAuthorId(),
								null, attrMap);
					}
				} else {
					return this.packModeAndView(request, "/common/error", "付费章节设置错误，请联系客服！", null);
				}
			} else {
				return this.packModeAndView(request, "/book/chapterContent", null, attrMap);
			}
		}
	}

}
